#include <chrono>
#include <thread>

#include "App.h"
#include "Global.h"
#include "Mainwin.h"
#include "ServiceManager.h"
#include "ModuleManager.h"

#include "ServiceConnection.h"

namespace Gnodroid
{

    Glib::RefPtr<Glib::MainContext>
    App::sm_rpMainContext {nullptr};

    ServiceManager*
    App::sm_pServiceManager {nullptr};

    ModuleManager*
    App::sm_pModuleManager {nullptr};

    App*
    App::sm_pApp {nullptr};

    Glib::RefPtr<App>
    App::create()
    {
        //不允许一个进程中拥有两个应用程序实例
        if (sm_pApp) {
            LOG_ERROR("can not new two app instance");
            return Glib::RefPtr<App>(nullptr);
        }

        App* app = new App();
        sm_pApp = app;
        Glib::RefPtr<App> rpApp (app);
        return rpApp;
    }

    App::App() :
        Gtk::Application("org.gnome.Gnodroid"),
        Glib::ObjectBase("gnd_app")
    {
        signal_activate().connect(sigc::mem_fun(*this, &App::__onActivate));
    }

    void
    App::__onActivate()
    {


        LOG("App activate");
        /*
        Gtk::Window* win = this->get_active_window();
        if (!win) {
            win = new Gnodroid::Mainwin();
            this->add_window(*win);
        }
        win->present();
*/
        //获取应用窗口
        m_pMainwin = static_cast<Mainwin*>(get_active_window());
        if (!m_pMainwin) {
            m_pMainwin = new Mainwin();
            add_window(*m_pMainwin);
        }
        m_pMainwin->present();
/*
        ServiceConnection* sc = static_cast<ServiceConnection*>(sm_pServiceManager->getService(SERVICE_CONNECTION));
        sc->startServerAsyn(sigc::slot<bool, bool>([](bool result)->bool{
            LOG("start server succed");
            //using namespace std::chrono_literals;
            //std::this_thread::sleep_for(5s);
        }));
        */

        //获取主线程Context
        sm_rpMainContext = Glib::MainContext::get_default();

        sm_pServiceManager = new ServiceManager();  //创建服务管理器
        sm_pModuleManager = new ModuleManager();    //创建模块管理器

        sm_pServiceManager->start();                //启动服务管理器
        sm_pModuleManager->start();                 //启动服务管理器


    }

    Glib::RefPtr<Glib::MainContext>
    App::getMainContext()
    {
        return App::sm_rpMainContext;
    }

    ServiceManager*
    App::getServiceManager()
    {
        return sm_pServiceManager;
    }

    ModuleManager*
    App::getModuleManager()
    {
        return sm_pModuleManager;
    }

    App*
    App::getCurrentApp()
    {
        return sm_pApp;
    }

    Mainwin*
    App::getMainwin()
    {
        return m_pMainwin;
    }


    Service*
    App::getService(ServiceId id)
    {
        if (!sm_pServiceManager) {
            return nullptr;
        }
        return sm_pServiceManager->getService(id);
    }

}
